package Controller.Sign;

import Model.SignModel.Sign;
import Model.User;
import Service.SignService;
import Service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import utils.permission.ConstantsUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/Sign")
public class SignController {

    @Autowired
    private SignService signService;
    @Autowired
    private UserService userService;

    @RequestMapping("/getSignList")
    @ResponseBody
    public PageInfo getSignList(@RequestParam(value = "pn", defaultValue = "1") Integer pn, @RequestParam(value = "limit", defaultValue = "10") Integer limit,HttpServletRequest request,Sign sign) throws ParseException {
        User user = (User) request.getSession().getAttribute(ConstantsUtils.SessionObj.CURRENT_USER);
        String Role_id=this.userService.findRoleIDbyUserNumber(user.getUser_number());
        if(Role_id.equals("2")){
            String settleCode =userService.findSettleCodebyUserNumber(user.getUser_number());
            System.out.println("找到机构代码："+settleCode);
            sign.setOrganization_id(settleCode);
            PageHelper.startPage(pn, limit);
            System.out.println("[根据时间差进行更新！]");
            signService.updateByTime(sign);
            System.out.println("[根据时间差进行更新(异常)！]");
            signService.updateAlarmByTime(sign);

            //转换字符串为时间格式
            String myDate = request.getParameter("f_sign");
            if (myDate==null){
                System.out.println("时间字段参数为空！");
            }else {
                System.out.println("时间字段参数为："+myDate);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date utilDate = simpleDateFormat.parse(myDate);
                sign.setF_sign(utilDate);
            }
            List<Sign> signList = signService.getSignList(sign);
            System.out.println("[获取到签到数据：]"+signList);
            PageInfo page = new PageInfo(signList);
            return page;
        }
        PageHelper.startPage(pn, limit);
        System.out.println("[根据时间差进行更新！]");
        signService.updateByTime(sign);
        System.out.println("[根据时间差进行更新(异常)！]");
        signService.updateAlarmByTime(sign);

        //转换字符串为时间格式
        String myDate = request.getParameter("f_sign");
        if (myDate==null){
            System.out.println("时间字段参数为空！");
        }else {
            System.out.println("时间字段参数为："+myDate);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date utilDate = simpleDateFormat.parse(myDate);
            sign.setF_sign(utilDate);
        }

        List<Sign> signList = signService.getSignList(sign);
        System.out.println("[获取到签到数据：]"+signList);
        PageInfo page = new PageInfo(signList);
        return page;
    }

    @RequestMapping("/getSignList_wechat")
    @ResponseBody
    public PageInfo getSignList_wechat(@RequestParam(value = "pn", defaultValue = "1") Integer pn, @RequestParam(value = "limit", defaultValue = "10") Integer limit,HttpServletRequest request,Sign sign) throws ParseException {
        PageHelper.startPage(pn, limit);
        System.out.println("[根据时间差进行更新！]");
        signService.updateByTime(sign);
        System.out.println("[根据时间差进行更新(异常)！]");
        signService.updateAlarmByTime(sign);

        //转换字符串为时间格式
        String myDate = request.getParameter("f_sign");
        if (myDate==null){
            System.out.println("时间字段参数为空！");
        }else {
            System.out.println("时间字段参数为："+myDate);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date utilDate = simpleDateFormat.parse(myDate);
            sign.setF_sign(utilDate);
        }

        List<Sign> signList = signService.getSignList(sign);
        System.out.println("[获取到签到数据：]"+signList);
        PageInfo page = new PageInfo(signList);
        return page;
    }


    @RequestMapping("/updateState")
    @ResponseBody
    public int updateState(Sign sign){
        int status = 0;// 对数据库插入、更新和删除操作要返回一个int类型的值
        try {
            signService.updateState(sign);
        }catch (Exception e){
            status = -1;
            e.printStackTrace();
        }
        return status;
    }

    @RequestMapping("/updateSignInfo")
    @ResponseBody
    public int updateSignInfo(Sign sign){
        int status = 0;
        try {
            signService.updateSignInfo(sign);
        }catch (Exception e){
            status = -1;
            e.printStackTrace();
        }
        return status;
    }

    @RequestMapping("/deleteSignList")
    @ResponseBody
    public int deleteSignList(int id){
        int status = 0;
        try{
            signService.deleteSignList(id);
        }catch (Exception e){
            status = -1;
            e.printStackTrace();

        }
        return status;
    }

    /**
     *新增记录
     */
    @RequestMapping("/addSignList")
    @ResponseBody
    public int addSignList(Sign sign){
        int status = 0;
        try{
            signService.addSign(sign);
        }catch (Exception e){
            status = -1;
            e.printStackTrace();
        }
        return status;
    }





    /**
     * 微信小程序上传图片
     * @return 返回状态值
     */
    @RequestMapping("/uploadImage")
    @ResponseBody
    public int uploadImage(HttpServletRequest request,HttpServletResponse response,HttpSession session,@Param("hg_name") String hg_name,@Param("lr_name") String lr_name) throws Exception{
        System.out.println("[开始上传图片！]");
        int status = -1;
        //获取项目的路径
        String realPath = request.getSession().getServletContext().getRealPath("/");
        MultipartHttpServletRequest req = null;
        if (request instanceof MultipartHttpServletRequest) {
            req = (MultipartHttpServletRequest)(request);
            //        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
            MultipartFile image = req.getFile("file");//"file"与前端传输图片的参数名相同

            //获取到当前的日期时间生成文件名防止文件名重复
            String filedata = this.getDate();

            //指定图片上传的路径
            String imgPath = realPath+"/uploader_images";
            //将个人文件夹拼接到路径
            imgPath = imgPath+"/"+hg_name;

            //判断属于护工的个人路径是否存在
            File file = new File(imgPath);
            if (file.exists()) {
                //创建文件夹
                System.out.println(hg_name+"文件夹已存在！");
            }else{
                boolean isCreatFile = file.mkdirs();
                if (isCreatFile){
                    System.out.println("创建了属于护工："+hg_name+"的文件夹！");
                }
            }

            imgPath = imgPath +"/"+filedata.substring(0,8);
            //判断当前日期文件夹是否存在
            File dataFile = new File(imgPath);
            if (dataFile.exists()) {
                //创建文件夹
                System.out.println("日期文件夹已存在！");
            }else{
                boolean isCreatFile = dataFile.mkdirs();
                if (isCreatFile){
                    System.out.println("创建了属于日期："+filedata.substring(0,8)+"的文件夹！");
                }
            }
            imgPath = imgPath +"/"+lr_name;
            File lrFile = new File(imgPath);
            //判断属于老人的文件是否存在
            if (lrFile.exists()) {
                //创建文件夹
                System.out.println(lr_name+"文件夹已存在！");
            }else{
                boolean isCreatFile = lrFile.mkdirs();
                if (isCreatFile){
                    System.out.println("创建了属于老人："+lr_name+"的文件夹！");
                }
            }

            //获取上传文件名
            String imageName = image.getOriginalFilename();
            //获取上传文件后缀
            assert imageName != null;
            String imageNameExtension = imageName.substring(imageName.lastIndexOf(".") + 1);

            //生成一个随机数
            int i = (int) (Math.random() * 1000);

            //生成新的文件名
            imageName = filedata + i + "." + imageNameExtension;

            //文件上传,保存到指定路径的本地磁盘
            try {
                image.transferTo(new File(imgPath, imageName));
                status = 0;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(status==0){
            System.out.println("[上传图片成功！]");
        }
        return status;
    }

    @RequestMapping("/uploadVideo")
    @ResponseBody
    public int uploadVideo(HttpServletRequest request,HttpServletResponse response,HttpSession session,@Param("hg_name") String hg_name,@Param("lr_name") String lr_name) throws Exception{
        System.out.println("[开始上传视频！]");
        int status = -1;
        //获取项目的路径
        String realPath = request.getSession().getServletContext().getRealPath("/");

        MultipartHttpServletRequest req = null;
        if (request instanceof MultipartHttpServletRequest) {
            req = (MultipartHttpServletRequest)(request);
            //        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
            MultipartFile video = req.getFile("file");//"file"与前端传输图片的参数名相同

            //获取到当前的日期时间生成文件名防止文件名重复
            String filedata = this.getDate();

            //指定视频上传的路径
            String videoPath = realPath+"/uploader_videos";
            //将个人文件夹拼接到路径
            videoPath = videoPath+"/"+hg_name;

            //判断该路径是否存在
            File file = new File(videoPath);
            if (file.exists()) {
                System.out.println(hg_name+"文件夹已存在！");
            }else{
                boolean isCreatFile = file.mkdirs();
                if (isCreatFile){
                    System.out.println("创建了属于"+hg_name+"的文件夹！");
                }
            }
            videoPath = videoPath +"/"+filedata.substring(0,8);
            //判断当前日期文件夹是否存在
            File dataFile = new File(videoPath);
            if (dataFile.exists()) {
                System.out.println("日期文件夹已存在！");
            }else{
                boolean isCreatFile = dataFile.mkdirs();
                if (isCreatFile){
                    System.out.println("创建了属于日期："+filedata.substring(0,8)+"的文件夹！");
                }
            }

            videoPath = videoPath +"/"+lr_name;
            File lrFile = new File(videoPath);
            //判断属于老人的文件是否存在
            if (lrFile.exists()) {
                System.out.println(lr_name+"文件夹已存在！");
            }else{
                boolean isCreatFile = lrFile.mkdirs();
                if (isCreatFile){
                    System.out.println("创建了属于老人："+lr_name+"的文件夹！");
                }
            }

            //获取上传文件名
            String videoName = video.getOriginalFilename();
            //获取上传文件后缀
            assert videoName != null;
            String videoNameExtension = videoName.substring(videoName.lastIndexOf(".") + 1);

            //生成一个随机数
            int i = (int) (Math.random() * 1000);

            //生成新的文件名
            videoName = filedata + i + "." + videoNameExtension;

            //文件上传,保存到指定路径的本地磁盘
            try {
                video.transferTo(new File(videoPath, videoName));
                status = 0;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(status==0){
            System.out.println("[上传视频成功！]");
        }
        return status;
    }
    /**
     * 获取当前日期时间的string类型用于文件名防重复
     * @return 返回时间的字符串
     */
    public String getDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        return formatter.format(currentTime);
    }

}
